﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GenUtil.Dto;
using ServiceLayer.Service.Impl;
using GenUtil;
using CrystalDecisions.CrystalReports.Engine;
using WebApp.Reports;
using System.Data;
using CrystalDecisions.Shared;
using System.IO;

namespace WebApp
{
    public partial class StudentRegister : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                LoadGrid();
            }


        }



        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                StudentDto studentDto = formToDto();
                ServiceLocator.getStudentService().InsertStudentDto(studentDto);
                LoadGrid();
                doClear();
                CustomValidator1.IsValid = false;
                CustomValidator1.ErrorMessage = "Submitted Successfully";
                return;
            }
        }
        private StudentDto formToDto()
        {
            StudentDto studentDto = new StudentDto();
            studentDto.FirstName = txtFirstName.Text.Trim();
            studentDto.LastName = txtLastName.Text.Trim();
            studentDto.Password = txtPassword.Text.Trim();
            studentDto.Department = txtDepartment.Text.Trim();
            studentDto.RollNo = txtRollNo.Text.Trim();
            studentDto.AddressNo1 = txtAddressNo1.Text.Trim();
            studentDto.AddressNo2 = txtAddressNo2.Text.Trim();
            studentDto.EmailId = txtEmailId.Text.Trim();
            return studentDto;
        }
        private void LoadGrid()
        {
            List<StudentDto> studentDtos = ServiceLocator.getStudentService().getStudentDtos();
            gvStudent.DataSource = studentDtos;
            gvStudent.DataBind();

        }
        private void doClear()
        {
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtPassword.Text = "";
            txtReTypePassword.Text = "";
            txtDepartment.Text = "";
            txtRollNo.Text = "";
            txtAddressNo1.Text = "";
            txtAddressNo2.Text = "";
            txtEmailId.Text = "";
            return;
        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }
        protected void gvStudent_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (txtReTypePassword.Text.Trim() == "")
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "Re-Type Password can not be blanked";
                return;
            }
            if (txtDepartment.Text.Trim() == "")
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "Department is required.";
                return;
            }
            if (txtRollNo.Text.Trim() == "")
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "Roll No. is required.";
                return;
            }
            if (txtAddressNo1.Text.Trim() == "")
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "Address No.1 is required.";
                return;
            }
            StudentDto studentDtoByRollNo = ServiceLocator.getStudentService().getStudentRecord(txtRollNo.Text.Trim());
            if (studentDtoByRollNo != null)
            {
                args.IsValid = false;
                CustomValidator1.ErrorMessage = "Roll No. is already exist.";
                return;
            }
            if (txtEmailId.Text.Trim() != "")
            {
                StudentDto studentDtoByEmailId = ServiceLocator.getStudentService().getStudentEmailId(txtEmailId.Text.Trim());
                if (studentDtoByEmailId != null)
                {
                    args.IsValid = false;
                    CustomValidator1.ErrorMessage = "Email Id is already exist.";
                    return;
                }
            }
        }

        protected void txtFirstName_TextChanged(object sender, EventArgs e)
        {

        }

        protected void btnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/StudentDefault.aspx");
        }

        protected void gvStudent_PageIndexChanged(object sender, EventArgs e)
        {
            LoadGrid();
        }

        protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvStudent.PageIndex = e.NewPageIndex;
        }

        protected void btnGenerateReport_Click(object sender, EventArgs e)
        {
            String path = "C:\\test\\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string filepath = path + "report1.pdf";
            DataSet ds = ServiceLocator.getStudentService().getDataSet();
            DataSet dstemp = new DataSet();
            dstemp.ReadXmlSchema(HttpContext.Current.Server.MapPath("~/Reports/CrystalReport.xsd"));
            DataTable dtTable = dstemp.Tables["STUDENT"];
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DataRow drTable = dtTable.NewRow();
                drTable["FIRST_NAME"] = ds.Tables[0].Rows[i]["FIRST_NAME"].ToString();
                drTable["LAST_NAME"] = ds.Tables[0].Rows[i]["LAST_NAME"].ToString();
                drTable["DEPARTMENT"] = ds.Tables[0].Rows[i]["DEPARTMENT"].ToString();
                drTable["ROLL_NO"] = ds.Tables[0].Rows[i]["ROLL_NO"].ToString();
                drTable["EMAIL_ID"] = ds.Tables[0].Rows[i]["EMAIL_ID"].ToString();
                dtTable.Rows.Add(drTable);
            }
            ReportDocument crystalReport = new ReportDocument();
            crystalReport.Load(HttpContext.Current.Server.MapPath("~/Reports/StudentReport.rpt"));
            crystalReport.SetDataSource(dstemp);            
            crystalReport.ExportToDisk(ExportFormatType.PortableDocFormat, filepath);
            //CreatePdfFile(ds, filepath);
            Session["filePath"] = filepath;
            string url = "<script language='javascript' type='text/javascript'>window.open('Billing/Display.aspx','','height=600,width=1050,status=yes,left=125,top=20,toolbar=no,menubar=no,scrollbars=yes,location=center,resizable=yes');</script>";
            Response.Write(url);
        }

        private void CreatePdfFile(DataSet ds, string filepath)
        {
            ReportDocument crystalReport = new ReportDocument();
            crystalReport.Load(HttpContext.Current.Server.MapPath("~/Reports/StudentReport.rpt"));            
            crystalReport.SetDataSource(ds);
            //crystalReport.SetDatabaseLogon("", "", "", "");
            crystalReport.ExportToDisk(ExportFormatType.PortableDocFormat, filepath);
        }
    }
}
